package com.zhangshuo.patternDesign.command;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by shuo.zhang on 2017-10-23.
 */
public class ProjectManager {

    private List<ITask> tasks = new ArrayList<>();
    private List<Programmer> programmers = new ArrayList<>();
    private static final int MAX_TASK_ONEDAY = 4 ;
    private int programmerIndex ;

    public void receiveTask(ITask task){
        tasks.add(task);
    }

    /**
     * 构造方法
     * @param programmers
     */
    public ProjectManager(Programmer... programmers) {
        this.programmers.addAll(Arrays.asList(programmers));
    }

    /**
     * 分配任务,在高并发的时候会出问题，需要加锁或者其它方式来解决下
     */
    public void assignTask(){
        ITask[] copy = new ITask[tasks.size() > MAX_TASK_ONEDAY ? tasks.size()-MAX_TASK_ONEDAY : 0];
        for(int i=0; i<=MAX_TASK_ONEDAY && i<tasks.size(); i++){
            tasks.get(i).handleTask(choiceProgrammer());
        }
        tasks = Arrays.asList(copy);
    }


    /**
     * 选择一个程序员
     * @return
     */
    public Programmer choiceProgrammer(){
        if (null == programmers || programmers.size()==0){
            throw new RuntimeException("没有程序员可用了,赶快招点过来吧....");
        }
        return programmers.get(programmerIndex>=programmers.size() ? 0:programmerIndex++);
    }

}
